package com.tre.jdevtemplateboot.common.util;

import com.tre.jdevtemplateboot.exception.business.SysParamValidatorException;
import com.tre.jdevtemplateboot.exception.business.SysUnAuthorizedException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.security.NoSuchAlgorithmException;

/**
 * @author JDev
 */
public class SqlInjectionUtils {

    private static final Logger logger = LoggerFactory.getLogger(SqlInjectionUtils.class);
    private static final String TABLE_DICT_SIGN_SALT = "jdev_dict_sign_salt";
    private static final String ERROR_MESSAGE = "SQL injection vulnerability signature verification failed.";
    private static final String SUCCESS_MESSAGE = "SQL injection vulnerability signature verification successful.";
    private static final String XSS_FILTER = YamlConfigurerUtil.getStrYmlVal("xss.filter-list");

    private SqlInjectionUtils() {
    }

    /**
     * 针对表进行sign签名校验（增加安全机制）
     *
     * @param dictCode
     * @param sign
     */
    public static void checkDictTableSign(String dictCode, String sign) {

        String accessToken = HttpUtils.getHttpServletRequest().getHeader(
                YamlConfigurerUtil.getStrYmlVal("com.tre.jdev.pre-user-issuer"));
        checkDictTableSignCommon(dictCode, sign, accessToken);
    }

    /**
     * 针对表进行sign签名校验（增加安全机制）
     *
     * @param dictCode
     * @param sign
     * @param accessToken
     */
    public static void checkDictTableSign(String dictCode, String sign, String accessToken) {
        checkDictTableSignCommon(dictCode, sign, accessToken);
    }

    private static void checkDictTableSignCommon(String dictCode, String sign, String accessToken) {
        String signString = dictCode + SqlInjectionUtils.TABLE_DICT_SIGN_SALT + accessToken;
        String securitySign = MD5Utils.inputPassToDbPass(signString);
        if (!securitySign.equals(sign)) {
            logger.error("{} {} != {} ,dictCode= {}", ERROR_MESSAGE, sign,securitySign, dictCode);
            throw new SysUnAuthorizedException(ERROR_MESSAGE);
        }
        logger.info("{} {} ,dictCode= {}", SUCCESS_MESSAGE, sign, dictCode);
    }

    /**
     * sql注入过滤处理，遇到注入关键字抛异常
     *
     * @param value
     */
    public static void filterContent(String value) {
        checkContent(value);
    }

    /**
     * sql注入过滤处理，遇到注入关键字抛异常
     *
     * @param values
     */
    public static void filterContent(String[] values) {
        for (String value : values) {
            checkContent(value);
        }
    }

    private static void checkContent(String value) {
        if (value == null || "".equals(value)) {
            return;
        }
        value = value.toLowerCase();
        String[] xssArr = XSS_FILTER.split("\\|");
        for (int i = 0; i < xssArr.length; i++) {
            if (value.indexOf(xssArr[i]) > -1) {
                logger.error("请注意，存在SQL注入关键词---> {}", xssArr[i]);
                logger.error("请注意，值可能存在SQL注入风险!---> {}", value);
                throw new SysParamValidatorException("请注意，值可能存在SQL注入风险!--->" + value);
            }
        }
    }
}
